<template>
  <div class="machineMaintain-detail">
    <n-card v-if="loading" :bordered="false" class="proCard">
      <n-spin :show="loading" class="loading" />
    </n-card>

    <DFPageDetail v-else :page-options="pageOptions">
      <template #projectList v-if="tableData && tableData.length > 0">
        <div class="sales-title">{{ t('machineMaintain.table.tableName') }}</div>
        <div class="list">
          <n-grid cols="2" item-responsive responsive="self" :x-gap="30" :y-gap="10">
            <n-grid-item span="2 400:2 600:2 800:1" v-for="(item, key) in tableData" :key="key">
              <n-card :class="['box-card', `${item.maintenanceResult === 1 ? 'box-err' : ''}`]">
                <div class="flex">
                  <div class="img-view">
                    <n-image
                      v-if="item.fileUrl && !isImageError"
                      class="img"
                      :src="baseUrl + item.fileUrl"
                      object-fit="fill"
                      @error="handleImageError"
                    />
                    <div class="image__error" v-if="isImageError && item.fileUrl">{{
                      t('machineMaintain.tipMsg.imgLoadError')
                    }}</div>
                    <div class="image__error" v-if="!item.fileUrl">{{
                      t('common.tipMsg.imgNotUpload')
                    }}</div>
                  </div>
                  <div class="project-content">
                    <n-descriptions label-placement="left" :title="item.projectName" :column="1">
                      <n-descriptions-item :label="t('machineMaintain.table.type')">
                        {{ item.periodRateName }}
                      </n-descriptions-item>
                      <n-descriptions-item :label="t('machineMaintain.table.unit')">
                        {{ item.unit }}
                      </n-descriptions-item>
                      <n-descriptions-item :label="t('machineMaintain.table.part')">
                        {{ item.part }}
                      </n-descriptions-item>
                      <n-descriptions-item :label="t('common.table.remark')">
                        {{ item.remark ? item.remark : '-' }}
                      </n-descriptions-item>
                    </n-descriptions>
                  </div>
                  <div class="btn-group" v-if="routerType === 'add'">
                    <div
                      :class="['btn', `${item.maintenanceStatus === 1 ? 'active' : ''}`]"
                      @click="item.maintenanceStatus = 1"
                    >
                      {{ t('machineMaintain.table.normal') }}
                    </div>
                    <div
                      :class="['btn', 'err', `${item.maintenanceStatus === 0 ? 'active' : ''}`]"
                      @click="item.maintenanceStatus = 0"
                    >
                      {{ t('machineMaintain.table.unNormal') }}
                    </div>
                  </div>
                </div>
              </n-card>
            </n-grid-item>
          </n-grid>
        </div>
      </template>
    </DFPageDetail>
  </div>
</template>

<script lang="ts" setup name="MachineMaintainDetail">
  import lang from '../lang';

  import { useMixins } from '@/hooks/useMixins';

  // import { dateFn } from '@/utils/http/axios/ipcIndex';

  import { useUserStore } from '@/store/modules/user';

  import {
    parseTime,
    // disablePreviousDate,
    getDateStr,
  } from '@/utils/dateUtil';

  import {
    addMachineMaintain,
    updateMachineMaintain,
    infoMachineMaintain,
  } from '@/api/wip/machineMaintain';
  import { getListMachineMaintainProject } from '@/api/base/machineMaintainProject';

  import type { FormItemRule } from 'naive-ui';

  const {
    t,
    loadLangFn,
    getDictDataListFn,
    routerType,
    message,
    // language
  } = useMixins();

  import { storage } from '@render/utils/Storage';

  const baseUrl = `http://${storage.get('host')}:3000/file/`;

  const loading = ref(false);

  loadLangFn(lang);
  const tableData: any = ref([]);
  // 设备名称列表
  const machineList: any = ref([]);

  const machineTypeList: any = ref([]);

  const maintenanceTypeList: any = ref([]);

  // const plannedMaintenanceDate = ref('');

  const userStore = useUserStore();

  const userInfo: object = userStore.getUserInfo || {};

  const userName = userInfo['userName'] || '';

  const isImageError = ref(false);

  const handleImageError = () => {
    isImageError.value = true;
  };

  async function getMachineTypeListDataFn() {
    const res = await Promise.all([
      getDictDataListFn('machine_type'),
      getDictDataListFn('maintenance_period_type'),
    ]);

    const [list1, list2] = res;

    machineTypeList.value = list1;
    maintenanceTypeList.value = list2;
  }

  const initFn = async () => {
    try {
      if (routerType !== 'check') {
        loading.value = true;
        // 发送请求获取下拉框数据
        await getMachineTypeListDataFn();

        loading.value = false;

        // setTimeout(() => {
        //   loading.value = false;
        // }, 000);
      }
    } catch (e) {
      console.log(e);
    }
  };

  const checkSubmitFn = (editTableData = []) => {
    let isSubmit = true;
    if (editTableData) {
      isSubmit = editTableData.every((item) => {
        return item.maintenanceStatus === 0 || item.maintenanceStatus === 1 ? true : false;
      });
    }
    if (!isSubmit) {
      message.error(`${t('machineMaintain.tipMsg.submitErr')}`);
    }

    return isSubmit;
  };

  const beforeSubmitFn = (data: any = {}, _refData: any = {}) => {
    data = {
      ...data,
      tableData: tableData.value,
    };

    return checkSubmitFn(data.tableData);
  };

  const handleEditDataFn = (res: any = {}) => {
    if (res) {
      const { data = {} } = res;
      tableData.value =
        data?.machineMaintainList.map((item) => {
          return {
            ...item,
            maintenanceStatus: Number(item.maintenanceStatus),
          };
        }) || [];
      let newMachineMaintainProjectList = {};
      data?.machineMaintainList.forEach((item) => {
        let { periodRateName, periodRateCode } = item;
        if (!newMachineMaintainProjectList[periodRateName]) {
          newMachineMaintainProjectList[periodRateName] = {
            periodRateName,
            periodRateCode,
            child: [],
          };
        }
        newMachineMaintainProjectList[periodRateName].child.push(item);
      });
      let list = Object.values(newMachineMaintainProjectList);

      maintenanceTypeList.value = list.map((item: any) => ({
        label: item.periodRateName,
        value: item.periodRateCode,
        child: item.child,
      }));
      if (routerType === 'check') {
        data.planMaintenanceDate = parseTime(data.planMaintenanceDate, '{y}-{m}-{d}');
      }
      return data;
    }
  };

  const pageOptions = {
    list: [
      {
        type: 'form',
        descriptionsLabelWidth: 110,
        formSchemas: [
          // 保养单号
          {
            label: 'machineMaintainCode',
            prop: 'machineMaintainCode',
            component: 'NInput',
            disabled: true,
            componentProps: {
              placeholder: '保存时自动生成',
            },
          },
          // 保养名称
          {
            label: 'machineMaintainName',
            prop: 'machineMaintainName',
            component: 'NInput',
            required: true,
          },
          // 设备名称
          {
            label: 'machineName',
            prop: 'machineName',
            checkProp: 'machineName',
            required: true,
            editDisabled: true,
            component: 'NSelect',
            options: machineList,
            componentProps: {
              onUpdateValue(_v: string, option: any, updateFormModelFn: any) {
                if (option) {
                  if (typeof updateFormModelFn === 'function') {
                    const { label, value, machineModel, machineMaintainProjectList } = option;

                    updateFormModelFn({
                      machineCode: value,
                      machineName: label,
                      machineModel,
                    });

                    let newMachineMaintainProjectList = {};
                    machineMaintainProjectList.forEach((item) => {
                      let { periodRateName, periodRateCode } = item;
                      if (!newMachineMaintainProjectList[periodRateName]) {
                        newMachineMaintainProjectList[periodRateName] = {
                          periodRateName,
                          periodRateCode,
                          child: [],
                        };
                      }
                      newMachineMaintainProjectList[periodRateName].child.push(item);
                    });
                    let list = Object.values(newMachineMaintainProjectList);

                    maintenanceTypeList.value = list.map((item: any) => ({
                      label: item.periodRateName,
                      value: item.periodRateCode,
                      child: item.child,
                    }));
                    updateFormModelFn({
                      periodRateName: maintenanceTypeList.value[0].label,
                      periodRateCode: maintenanceTypeList.value[0].value,
                    });
                    tableData.value = maintenanceTypeList.value[0].child || [];
                  }
                } else {
                  typeof updateFormModelFn === 'function' &&
                    updateFormModelFn({
                      machineCode: null,
                      machineName: null,
                      machineModel: null,
                    });
                }
              },
            },
          },
          // 设备编码
          {
            label: 'machineCode',
            component: 'NInput',
            common: true,
            disabled: true,
          },
          // 设备型号
          {
            label: 'machineModel',
            component: 'NInput',
            disabled: true,
          },
          // 设备类型
          // {
          //   label: 'machineType',
          //   component: 'NSelect',
          //   options: machineTypeList,
          //   disabled: true,
          // },
          // 保养类型
          {
            label: 'periodRateName',
            component: 'NSelect',
            prop: 'periodRateCode',
            checkProp: 'periodRateName',
            options: maintenanceTypeList,
            editDisabled: true,
            required: true,
            componentProps: {
              onUpdateValue(_v: string, option: any, updateFormModelFn: any) {
                if (option) {
                  if (typeof updateFormModelFn === 'function') {
                    const { label, value, child } = option;
                    updateFormModelFn({
                      periodRateCode: value,
                      periodRateName: label,
                    });
                    tableData.value = child;
                  }
                } else {
                  typeof updateFormModelFn === 'function' &&
                    updateFormModelFn({
                      periodRateCode: null,
                      periodRateName: null,
                    });
                }
              },
            },
          },
          // 计划保养日期
          {
            component: 'NDatePicker',
            label: 'planMaintenanceDate',
            defaultValue: new Date(getDateStr(0)).getTime(),
            componentProps: {
              clearable: true,
              format: 'yyyy-MM-dd',
              valueFormat: 'yyyy-MM-dd',
              type: 'date',
            },
            rules: [
              {
                required: true,
                validator(_rule: FormItemRule, value: string) {
                  if (!value) {
                    return new Error(t('common.formTipMsg.select'));
                  }
                },
                trigger: ['change'],
              },
            ],
          },
          // 保养人
          {
            label: 'maintenanceUser',
            component: 'NInput',
            required: true,
            defaultValue: userName,
            hidden: routerType !== 'add',
          },
          {
            label: 'remark',
            type: 'textarea',
            common: true,
            giProps: { span: 3 },
            componentProps: {
              'show-count': true,
            },
          },
        ],
      },
      {
        type: 'slot',
        slotName: 'projectList',
        hiddenTitle: true,
      },
    ],
    formLabelWidthEn: 100,
    descriptionsListLabelWidthEn: 150,
    routeName: 'machineMaintain',
    addDataFn: addMachineMaintain,
    updateDataFn: updateMachineMaintain,
    getDataFn: infoMachineMaintain,
    beforeSubmitFn,
    handleEditDataFn,
    setSubmitDataFn: (data) => {
      const maintenanceStatus = tableData.value.every((item) => {
        return item.maintenanceStatus === 1;
      });
      data = {
        ...data,
        maintenanceStatus: maintenanceStatus ? '1' : '0',
        machineMaintainList: tableData.value.map((item) => {
          delete item.id;
          return {
            ...item,
          };
        }),
      };
      return data;
    },
  };

  // 获取设备名称
  const getMachineNameFn = async () => {
    const res = await Promise.all([getListMachineMaintainProject()]);
    const [list] = res;

    machineList.value =
      list?.data.map((item) => ({
        label: item.machineName,
        value: item.machineCode,
        machineModel: item.machineModel,
        machineMaintainProjectList: item.machineMaintainProjectList,
      })) || [];
  };
  getMachineNameFn();

  initFn();
</script>

<style lang="less" scoped>
  .standardProgramme-detail {
    position: relative;
    .loading {
      width: 100%;
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
  }
  .sales-title {
    font-size: 16px;
    font-weight: 600;
    padding: 0;
    line-height: 24px;
    position: relative;
    color: #31373d;
    margin-bottom: 16px;
  }
  .sales-title {
    margin-top: 30px;
  }
  .list {
    .n-card {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      border: 1px solid #d9d9d9;
      border-radius: 4px;
      box-shadow: 1px 2px 4px 0px rgba(153, 153, 153, 0.3);
      margin-bottom: 24px;
      position: relative;
      &.box-err {
        border-color: #f1434c;
        transition: 0.3s all;
      }
      .img-view {
        width: 38.65%;
        max-width: 300px;
        display: block;
        margin-right: 3.74%;
        position: relative;
        max-height: 216px;

        .is-normal {
          position: absolute;
          left: 0;
          right: 0;
          width: 100%;
          height: 32px;
          line-height: 32px;
          bottom: 0;
          background: rgba(82, 197, 112, 0.5);
          border-radius: 0px 0px 4px 4px;
          font-size: 16px;
          color: #ffffff;
          text-align: center;
          &.unNormal {
            background: rgba(241, 67, 76, 0.5);
          }
        }
        .img {
          width: 100%;
          max-width: 300px;
          //   height: 216px;
          // height: 100%;
        }
        .image__error {
          display: flex;
          justify-content: center;
          align-items: center;
          min-height: 216px;
          background: #f3f3f3;
          color: #999999;
        }
        .tips {
          position: absolute;
          left: 0;
          right: 0;
          width: 100%;
          height: 32px;
          bottom: 0;
          background: rgba(82, 197, 112, 0.5);
          border-radius: 0px 0px 4px 4px;
          font-size: 16px;
          color: #ffffff;
          &.unNormal {
            background: rgba(241, 67, 76, 0.5);
          }
        }
      }
      .btn-group {
        flex: 1;
        display: flex;
        flex-direction: row;
        justify-content: flex-end;
        .btn {
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 14px;
          color: #999999;
          border: 1px solid;
          border-color: #d9d9d9;
          border-radius: 16px;
          height: 32px;
          min-width: 76px;
          margin: 0 4px;
          font-weight: normal;
          &:last-child {
            margin-right: 0;
          }
          cursor: pointer;
          transition: 0.3s all;
          word-break: keep-all;
          &.active {
            background-color: #52c570;
            border-color: #52c570;
            color: #fff;
            transition: 0.3s all;
            &:hover {
              color: #fff;
              transition: 0.3s all;
            }
          }
          &:hover {
            color: #52c570;
            border-color: #52c570;
            transition: 0.3s all;
          }
          &.err {
            &:hover {
              color: #f1434c;
              border-color: #f1434c;
              transition: 0.3s all;
            }
            &.active {
              background-color: #f1434c;
              border-color: #f1434c;
              transition: 0.3s all;
              &:hover {
                color: #fff;
              }
            }
          }
        }
      }
    }
  }
</style>
